/**
 * HTML代码管理列表页面
 * 显示HTML代码列表，支持搜索、筛选、分页等功能
 * 使用项目统一的UI组件保持界面一致性
 */

import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  useHtmlCodes, 
  useDeleteHtmlCode 
} from '../../lib/api/hooks/use-api.js';
import { Container } from '@/components/common/container';
import { Toolbar, ToolbarActions, ToolbarHeading } from '@/layouts/demo1/components/toolbar';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { TableBody } from '@/components/ui/table';
import { ResponsiveTable, ResponsiveTableHeader, ResponsiveTableRow, ResponsiveTableHead, ResponsiveTableCell, TableLoading, TableEmpty } from '@/components/ui/responsive-table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Eye, Edit, Trash2, Search, Filter, Plus, Code, FileText } from 'lucide-react';

/**
 * HTML代码管理列表页面组件
 * 提供HTML代码的列表展示、搜索、筛选、分页等功能
 */
const HtmlCodeListPage = () => {
  // 路由导航钩子
  const navigate = useNavigate();
  
  // 搜索和筛选状态
  const [searchTerm, setSearchTerm] = useState(''); // 搜索关键词
  const [workspaceFilter, setWorkspaceFilter] = useState(''); // 工作空间筛选
  const [appFilter, setAppFilter] = useState(''); // 应用筛选
  const [currentPage, setCurrentPage] = useState(1); // 当前页码
  const [pageSize, setPageSize] = useState(10); // 每页数量

  // 构建查询参数对象
  const queryParams = useMemo(() => ({
    page: currentPage,
    pageSize: pageSize,
    search: searchTerm,
    workspaceId: workspaceFilter,
    appId: appFilter,
  }), [currentPage, pageSize, searchTerm, workspaceFilter, appFilter]);

  // 使用React Query获取HTML代码列表数据
  const { 
    data: htmlCodesData, 
    isLoading, 
    error, 
    refetch 
  } = useHtmlCodes(queryParams);

  // 删除HTML代码的变更操作
  const deleteHtmlCodeMutation = useDeleteHtmlCode({
    onSuccess: () => {
      // 删除成功后刷新列表
      refetch();
    },
    onError: (error) => {
      console.error('删除HTML代码失败:', error);
    }
  });

  // 处理新建HTML代码
  const handleCreateHtmlCode = () => {
    navigate('/html-code-management/create');
  };

  // 处理编辑HTML代码
  const handleEditHtmlCode = (htmlCode) => {
    navigate(`/html-code-management/edit/${htmlCode.id}`);
  };

  // 处理查看HTML代码详情
  const handleViewHtmlCode = (htmlCode) => {
    navigate(`/html-code-management/detail/${htmlCode.id}`);
  };

  // 处理删除HTML代码
  const handleDeleteHtmlCode = (htmlCode) => {
    if (confirm(`确定要删除HTML代码"${htmlCode.name}"吗？`)) {
      deleteHtmlCodeMutation.mutate(htmlCode.id);
    }
  };

  // 处理搜索
  const handleSearch = (value) => {
    setSearchTerm(value);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理筛选
  const handleFilterChange = (type, value) => {
    if (type === 'workspace') {
      setWorkspaceFilter(value);
    } else if (type === 'app') {
      setAppFilter(value);
    }
    setCurrentPage(1); // 重置到第一页
  };

  // 处理分页变化
  const handlePageChange = (page, size) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 渲染表格数据行
  const renderTableRows = () => {
    if (!htmlCodesData?.data) return [];
    
    return htmlCodesData.data.map((htmlCode) => (
      <ResponsiveTableRow key={htmlCode.id}>
        <ResponsiveTableCell>
          <div className="flex items-center gap-2">
            <Code className="size-4 text-muted-foreground" />
            <span className="font-medium">{htmlCode.name || '未命名'}</span>
          </div>
        </ResponsiveTableCell>
        <ResponsiveTableCell>
          <Badge variant="outline" size="md">
            {htmlCode.workspace_id || '未设置'}
          </Badge>
        </ResponsiveTableCell>
        <ResponsiveTableCell>
          <Badge variant="outline" size="md">
            {htmlCode.app_id || '未设置'}
          </Badge>
        </ResponsiveTableCell>
        <ResponsiveTableCell>
          <span className="text-muted-foreground max-w-md line-clamp-2">
            {htmlCode.content || '无描述'}
          </span>
        </ResponsiveTableCell>
        <ResponsiveTableCell>
          <div className="flex items-center gap-1">
            <FileText className="size-3 text-muted-foreground" />
            <span className="text-xs text-muted-foreground">
              {htmlCode.page ? `${htmlCode.page.length} 字符` : '无内容'}
            </span>
          </div>
        </ResponsiveTableCell>
        <ResponsiveTableCell>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleViewHtmlCode(htmlCode)}
              title="查看详情"
            >
              <Eye className="size-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEditHtmlCode(htmlCode)}
              title="编辑"
            >
              <Edit className="size-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleDeleteHtmlCode(htmlCode)}
              title="删除"
              className="text-destructive hover:text-destructive"
            >
              <Trash2 className="size-4" />
            </Button>
          </div>
        </ResponsiveTableCell>
      </ResponsiveTableRow>
    ));
  };

  return (
    <>
      {/* 页面标题和操作栏 */}
      <Container>
        <Toolbar>
          <ToolbarHeading
            title="页面对象管理"
            description="管理页面对象，支持查看、编辑、删除等操作"
          />
          <ToolbarActions>
            <Button onClick={handleCreateHtmlCode}>
              <Plus className="size-4 me-2" />
              新建页面对象
            </Button>
          </ToolbarActions>
        </Toolbar>
      </Container>

      {/* 搜索和筛选区域 */}
      <Container>
        <Card>
          <CardHeader>
            <CardTitle>搜索和筛选</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap items-center gap-4">
              {/* 搜索框 */}
              <div className="flex-1 min-w-64">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 size-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索页面名称或内容描述..."
                    value={searchTerm}
                    onChange={(e) => handleSearch(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>

              {/* 工作空间筛选 */}
              <Select
                value={workspaceFilter || "all"}
                onValueChange={(value) => handleFilterChange('workspace', value === "all" ? "" : value)}
              >
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择工作空间" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部工作空间</SelectItem>
                  <SelectItem value="workspace1">工作空间1</SelectItem>
                  <SelectItem value="workspace2">工作空间2</SelectItem>
                  <SelectItem value="workspace3">工作空间3</SelectItem>
                </SelectContent>
              </Select>

              {/* 应用筛选 */}
              <Select
                value={appFilter || "all"}
                onValueChange={(value) => handleFilterChange('app', value === "all" ? "" : value)}
              >
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择应用" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部应用</SelectItem>
                  <SelectItem value="app1">应用1</SelectItem>
                  <SelectItem value="app2">应用2</SelectItem>
                  <SelectItem value="app3">应用3</SelectItem>
                </SelectContent>
              </Select>

              {/* 刷新按钮 */}
              <Button
                variant="outline"
                onClick={() => refetch()}
                disabled={isLoading}
              >
                <Filter className="size-4 me-2" />
                刷新
              </Button>
            </div>
          </CardContent>
        </Card>
      </Container>

      {/* HTML代码列表 */}
      <Container>
        <Card>
          <CardHeader>
            <CardTitle>HTML代码列表</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveTable>
              <ResponsiveTableHeader>
                <ResponsiveTableRow>
                  <ResponsiveTableHead>页面名称</ResponsiveTableHead>
                  <ResponsiveTableHead>工作空间</ResponsiveTableHead>
                  <ResponsiveTableHead>应用程序</ResponsiveTableHead>
                  <ResponsiveTableHead>内容描述</ResponsiveTableHead>
                  <ResponsiveTableHead>页面HTML代码</ResponsiveTableHead>
                  <ResponsiveTableHead>操作</ResponsiveTableHead>
                </ResponsiveTableRow>
              </ResponsiveTableHeader>
              <TableBody>
                {isLoading ? (
                  <TableLoading colSpan={6} />
                ) : error ? (
                  <ResponsiveTableRow>
                    <ResponsiveTableCell colSpan={6} className="text-center py-8">
                      <div className="flex flex-col items-center gap-4">
                        <p className="text-destructive">加载失败: {error.message}</p>
                        <Button 
                          variant="outline" 
                          onClick={() => refetch()}
                        >
                          重试
                        </Button>
                      </div>
                    </ResponsiveTableCell>
                  </ResponsiveTableRow>
                ) : !htmlCodesData?.data?.length ? (
                  <TableEmpty 
                    colSpan={6}
                    message="暂无页面对象，点击上方按钮开始创建"
                  />
                ) : (
                  renderTableRows()
                )}
              </TableBody>
            </ResponsiveTable>

            {/* 分页信息 */}
            {htmlCodesData?.pagination && (
              <div className="flex items-center justify-between mt-4 pt-4 border-t">
                <div className="text-sm text-muted-foreground">
                  共 {htmlCodesData.pagination.total} 条记录，
                  第 {htmlCodesData.pagination.page} / {htmlCodesData.pagination.totalPages} 页
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(currentPage - 1, pageSize)}
                    disabled={currentPage <= 1}
                  >
                    上一页
                  </Button>
                  <span className="text-sm">
                    {currentPage} / {htmlCodesData.pagination.totalPages}
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(currentPage + 1, pageSize)}
                    disabled={currentPage >= htmlCodesData.pagination.totalPages}
                  >
                    下一页
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </Container>
    </>
  );
};

export default HtmlCodeListPage;